import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Logger, BadRequestException, Request } from '@nestjs/common';
import { QuestionsService } from './questions.service';
import { Question } from '@prisma/client';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { CreateQuestionDto } from './dto/create-question.dto';
import { UpdateQuestionDto } from './dto/update-question.dto';

@Controller('questions')
@UseGuards(JwtAuthGuard, RolesGuard)
export class QuestionsController {
  private readonly logger = new Logger(QuestionsController.name);

  constructor(private readonly questionsService: QuestionsService) {}

  @Post()
  @Roles('TEACHER')
  async create(@Body() createQuestionDto: CreateQuestionDto, @Request() req): Promise<Question> {
    this.logger.log(`创建新题目: ${createQuestionDto.content}`);
    try {
      return await this.questionsService.createQuestion({
        ...createQuestionDto,
        options: JSON.stringify(createQuestionDto.options),
        score: createQuestionDto.score || 1.0,
        createdBy: {
          connect: { id: req.user.id }
        }
      });
    } catch (error) {
      this.logger.error(`创建题目失败: ${error.message}`);
      throw new BadRequestException('创建题目失败');
    }
  }

  @Get()
  async findAll(): Promise<Question[]> {
    this.logger.log('获取所有题目');
    try {
      return await this.questionsService.questions({});
    } catch (error) {
      this.logger.error(`获取题目列表失败: ${error.message}`);
      throw new BadRequestException('获取题目列表失败');
    }
  }

  @Get(':id')
  async findOne(@Param('id') id: string): Promise<Question> {
    this.logger.log(`获取题目详情: ${id}`);
    try {
      const question = await this.questionsService.question({ id: Number(id) });
      if (!question) {
        throw new BadRequestException('题目不存在');
      }
      return question;
    } catch (error) {
      this.logger.error(`获取题目详情失败: ${error.message}`);
      throw new BadRequestException(error.message);
    }
  }

  @Patch(':id')
  async update(
    @Param('id') id: string,
    @Body() updateQuestionDto: UpdateQuestionDto,
  ): Promise<Question> {
    this.logger.log(`更新题目: ${id}`);
    try {
      return await this.questionsService.updateQuestion({
        where: { id: Number(id) },
        data: {
          ...updateQuestionDto,
          options: updateQuestionDto.options ? JSON.stringify(updateQuestionDto.options) : undefined
        },
      });
    } catch (error) {
      this.logger.error(`更新题目失败: ${error.message}`);
      throw new BadRequestException('更新题目失败');
    }
  }

  @Delete(':id')
  async remove(@Param('id') id: string): Promise<Question> {
    this.logger.log(`删除题目: ${id}`);
    try {
      return await this.questionsService.deleteQuestion({ id: Number(id) });
    } catch (error) {
      this.logger.error(`删除题目失败: ${error.message}`);
      throw new BadRequestException('删除题目失败');
    }
  }
}